<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="75px">
      <el-form-item label="用户账号" prop="userName">
        <el-input v-model="queryParams.userName" placeholder="请输入用户账号" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="用户姓名" prop="nickName">
        <el-input v-model="queryParams.nickName" placeholder="请输入用户昵称" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="手机号码" prop="phonenumber">
        <el-input v-model="queryParams.phonenumber" placeholder="请输入手机号码" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                   v-hasPermi="['business:userCert:export']">导出
        </el-button>
        <el-button type="success" plain icon="el-icon-check" size="mini" :disabled="multiple"
                   @click="handleAllowExamChange('',true)"
                   v-hasPermi="['business:user:changeUserAllowExam']">批量免学
        </el-button>
        <el-button type="danger" plain icon="el-icon-close" size="mini" :disabled="multiple"
                   @click="handleAllowExamChange('',false)"
                   v-hasPermi="['business:user:changeUserAllowExam']">批量必学
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="用户ID" align="center" prop="userId" v-if="false"/>
      <el-table-column label="用户账号" align="center" prop="userName"/>
      <el-table-column label="用户姓名" align="center" prop="nickName"/>
      <el-table-column label="手机号码" align="center" prop="phonenumber"/>
      <el-table-column label="工作地点" align="center" prop="workPlace"/>
      <el-table-column label="工作单位" align="center" prop="workUnit"/>
      <el-table-column label="免学考试" align="center" key="allowExam">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.allowExam"
                     @change="handleAllowExamChange(scope.row,scope.row.allowExam)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="帐号状态" align="center" key="status">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.status" active-value="0" inactive-value="1"
                     @change="handleStatusChange(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-user" @click="handleUser(scope.row)">用户管理</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-lock" @click="handleResetPwd(scope.row)">重置密码</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>
    <!-- 添加或修改用户配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="40%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item class="text-center" label="用户头像" prop="avatar">
              <userAvatar @updateProfile="updateProfile" :user="form" :avatar="form.avatar"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户昵称" prop="nickName">
              <el-input v-model="form.nickName" placeholder="请输入用户昵称" maxlength="30"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户性别" prop="sex">
              <el-select style="width: 100%;" v-model="form.sex" placeholder="请选择性别">
                <el-option v-for="dict in dict.type.sys_user_sex" :key="dict.value" :label="dict.label"
                           :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="phonenumber">
              <el-input v-model="form.phonenumber" placeholder="请输入手机号码" maxlength="11"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入邮箱" maxlength="50"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="工作地点" prop="workPlace">
              <el-select style="width: 100%;" v-model="form.workPlace" placeholder="请选择工作地点">
                <el-option v-for="(dict,index) in placeOption" :key="index" :label="dict.name"
                           :value="dict.name"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工作单位" prop="workUnit">
              <el-select style="width: 75%;" v-model="form.workUnit" placeholder="请选择工作单位">
                <el-option v-for="(dict,index) in workOption" :key="index" :label="dict.companyName"
                           :value="dict.companyName"></el-option>
              </el-select>
              <el-button style="margin-left: 10px;" size="mini" type="text" @click="handleCompany">新增企业</el-button>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input :rows="5" v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!--    -->
    <el-drawer :title="'用户名：' + formDetail.nickName" :visible.sync="drawer" size="75%">
      <div class="ml20 mr20">
        <el-tabs v-model="activeName" type="" @tab-click="handleClick">
          <el-tab-pane label="订单管理" name="first">
            <OrderInfo :createBy="formDetail.userName" :activeName="activeName"></OrderInfo>
          </el-tab-pane>
          <el-tab-pane label="用户学习情况" name="sixty">
            <UserVideo :createBy="formDetail.userName" :activeName="activeName"></UserVideo>
          </el-tab-pane>
          <el-tab-pane label="用户考试情况" name="seventy">
            <AnswerInfo :createBy="formDetail.userName" :platformId="formDetail.baseId" :type="'0'.toString()"
                        :activeName="activeName"></AnswerInfo>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import {
  listUser,
  changeUserStatus,
  getArea,
  companyList,
  addCompany,
  changeUserAllowExam
} from "@/api/business/businessUser";
import {
  getUser,
  delUser,
  addUser,
  updateUser1,
  resetUserPwd,
  deptTreeSelect
} from "@/api/system/user";
import userAvatar from "@/views/system/user/profile/userAvatar";
import OrderInfo from "../orderInfo/index.vue";
import UserVideo from "../userVideo/index.vue";
import AnswerInfo from "../answerInfo/index.vue";

export default {
  name: "BusinessUser",
  components: {
    OrderInfo,
    UserVideo,
    AnswerInfo,
    userAvatar
  },
  dicts: ['sys_normal_disable', 'sys_user_sex'],
  data() {
    return {
      // 表单参数
      formDetail: {},
      drawer: false,
      activeName: 'first',

      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户信息表格数据
      userList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        nickName: undefined,
        phonenumber: undefined,
        status: undefined,
        workPlace: undefined,
        workUnit: undefined,
        loginIp: undefined,
        loginDate: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        nickName: [{
          required: true,
          message: "用户昵称不能为空",
          trigger: "blur"
        }],
        sex: [{
          required: true,
          message: "性别不能为空",
          trigger: "blur"
        }],
        email: [{
          required: true,
          message: "邮箱不能为空",
          trigger: "change"
        }, {
          type: "email",
          message: "请输入正确的邮箱地址",
          trigger: ["blur", "change"]
        }],
        phonenumber: [{
          required: true,
          message: "手机号码不能为空",
          trigger: "blur"
        }, {
          pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
          message: "请输入正确的手机号码",
          trigger: "blur"
        }],
        workPlace: [{
          required: true,
          message: "工作地点不能为空",
          trigger: "change"
        }],
        workUnit: [{
          required: true,
          message: "工作单位不能为空",
          trigger: "change"
        }],
      },
      placeOption: [],
      workOption: []
    };
  },
  created() {
    this.getList();
    getArea().then(res => {
      this.placeOption = res.data
    })
  },
  methods: {
    getCompany() {
      companyList(this.form.userName).then(res => {
        this.workOption = res.data
      })
    },
    handleClick(tab) {
      this.activeName = tab.name;
    },
    /** 查询用户信息列表 */
    getList() {
      this.loading = true;
      listUser(this.queryParams).then(response => {
        this.userList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        userId: undefined,
        deptId: undefined,
        userName: undefined,
        nickName: undefined,
        userType: undefined,
        email: undefined,
        phonenumber: undefined,
        sex: undefined,
        avatar: undefined,
        password: undefined,
        status: undefined,
        workPlace: undefined,
        workUnit: undefined,
        delFlag: undefined,
        loginIp: undefined,
        loginDate: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        remark: undefined
      };
      this.resetForm("form");
    },
    updateProfile(img) {
      this.form.avatar = img
    },
    // 用户状态修改
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用";
      this.$modal.confirm('确认要"' + text + '""' + row.userName + '"用户吗？').then(function () {
        return changeUserStatus(row.userId, row.status);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function () {
        row.status = row.status === "0" ? "1" : "0";
      });
    },
    handleAllowExamChange(row, allowExam) {
      const baseIds = row.userId || this.ids;
      let text = allowExam ? "允许" : "禁止";
      this.$modal.confirm('确认要"' + text + '"用户免学考试吗？').then(function () {
        return changeUserAllowExam(baseIds, allowExam);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(() => {
      }).finally(() => {
        this.getList();
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.userId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    handleUser(row) {
      this.activeName = 'first';
      this.drawer = true;
      this.formDetail = row;
    },
    /** 重置密码按钮操作 */
    handleResetPwd(row) {
      this.$prompt('请输入"' + row.userName + '"的新密码', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false,
        inputPattern: /^.{5,20}$/,
        inputErrorMessage: "用户密码长度必须介于 5 和 20 之间"
      }).then(({
                 value
               }) => {
        resetUserPwd(row.userId, value).then(response => {
          this.$modal.msgSuccess("修改成功，新密码是：" + value);
        });
      }).catch(() => {
      });
    },
    handleCompany() {
      let that = this
      this.$prompt(
        '企业名称：',
        '新增', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputValue: '',
          inputErrorMessage: '输入不能为空',
          inputValidator: (value) => { // 点击按钮时，对文本框里面的值进行验证
            if (!value) {
              return '输入不能为空';
            }
          },
          callback: function (action, instance) {
            if (action === 'confirm') {
              addCompany({
                companyName: instance.inputValue,
                createBy: that.form.userName
              }).then(response => {
                if (response.code == 200) {
                  that.$modal.msgSuccess('新增成功！');
                  that.getCompany()
                } else {
                  that.$modal.alertWarning(response.msg);
                }
              });
            }
          }
        }).then(({
                   value
                 }) => {
      }).catch((err) => {
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const userId = row.userId || this.ids;
      getUser(userId).then(response => {
        this.form = response.data.user;
        this.open = true;
        this.title = "修改用户";
        this.getCompany()
        this.form.password = "";
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.userId != undefined) {
            updateUser1(this.form, 1).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addUser(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('/business/user/export', {
        ...this.queryParams
      }, `userInfo_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
